import multer from 'multer'
import path from 'path'
import fs from 'fs'
import { Request } from 'express'

// 确保上传目录存在
const uploadDir = path.join(__dirname, '../../uploads')
const avatarDir = path.join(uploadDir, 'avatars')

if (!fs.existsSync(uploadDir)) {
  fs.mkdirSync(uploadDir, { recursive: true })
}
if (!fs.existsSync(avatarDir)) {
  fs.mkdirSync(avatarDir, { recursive: true })
}

// 配置存储
const storage = multer.diskStorage({
  destination: (_req: Request, _file: Express.Multer.File, cb) => {
    cb(null, avatarDir)
  },
  filename: (_req: Request, file: Express.Multer.File, cb) => {
    // 生成唯一文件名：时间戳 + 随机数 + 原扩展名
    const timestamp = Date.now()
    const random = Math.round(Math.random() * 1E9)
    const ext = path.extname(file.originalname)
    const filename = `${timestamp}_${random}${ext}`
    cb(null, filename)
  }
})

// 文件过滤器
const fileFilter = (_req: Request, file: Express.Multer.File, cb: multer.FileFilterCallback) => {
  // 只允许图片文件
  if (file.mimetype.startsWith('image/')) {
    cb(null, true)
  } else {
    cb(new Error('只允许上传图片文件'))
  }
}

// 创建multer实例
const upload = multer({
  storage,
  fileFilter,
  limits: {
    fileSize: 2 * 1024 * 1024, // 2MB
    files: 1 // 一次只能上传一个文件
  }
})

// 头像上传中间件
export const uploadAvatar = upload.single('avatar')

// 获取文件URL
export const getFileUrl = (filename: string) => {
  return `/uploads/avatars/${filename}`
}

// 删除文件
export const deleteFile = (filename: string) => {
  const filePath = path.join(avatarDir, filename)
  if (fs.existsSync(filePath)) {
    fs.unlinkSync(filePath)
  }
} 